<?php
//创建任务
function bzg_generate_thumbnail_add_cron() {
	if( ! wp_next_scheduled( 'generate_thumbnail' ) ) {
		wp_schedule_event( time(), 'hourly', 'generate_thumbnail' );
		return true;
	}
	return false;
}

//删除任务
function bzg_generate_thumbnail_delete_cron() {
	if( wp_next_scheduled( 'generate_thumbnail' ) ) {
		wp_clear_scheduled_hook( 'generate_thumbnail' );
	}
}

//获取WordPress所有图片ID
function bzg_generate_thumbnail_get_attachment_ids(){
	$ids = array();
	$args = array(
		'posts_per_page' => -1,
		'post_type' => 'attachment',
		'post_mime_type' => 'image',
		'post_status' => 'closed',
	);
	$query = new WP_Query( $args );
	while ( $query->have_posts() ) {
		$query->the_post();
		$ids[] = get_the_ID();
	}
	wp_reset_postdata();
	return $ids;
}

//根据图片地址获取图片ID
function bzg_get_attachment_id_from_src( $src ) {
	global $wpdb;
	$src = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif|webp)$)/i', '', $src);
	return $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE guid='$src' LIMIT 1");
}

//删除缩略图尺寸medium_large
if( get_option( 'generate_thumbnail_medium_large' ) == 'no' ) {
	function bzg_generate_filter_image_sizes( $sizes ) {
		unset( $sizes['medium_large']);
		return $sizes;
	}
	add_filter( 'intermediate_image_sizes_advanced', 'bzg_generate_filter_image_sizes' );
}

//任务执行函数
function bzg_generate_thumbnail_cron_fun() {
	$attachment_ids = get_option( 'generate_thumbnail_ids' );

	$blogname = get_bloginfo( 'name' );
	$adminemail = get_bloginfo('admin_email');

	if( ! empty( $attachment_ids ) ) {
		$attachment_ids = explode( ',', $attachment_ids );
	}

	if( empty( $attachment_ids ) ) {
		$attachment_ids = bzg_generate_thumbnail_get_attachment_ids();
	}

	if( empty( $attachment_ids ) ) {
		bzg_generate_thumbnail_delete_cron();
		//发邮件
		$mail_title = get_bloginfo('name') . '重新生成缩略图任务执行失败';
		$mail_txt = $mail_title . " \n";
		$mail_txt .= '失败原因可能是图片不存在。';
		$headers[] = 'From: '. $blogname .' < ' . $adminemail . '>';
		wp_mail( $blogname . ' <' . $adminemail . '>', $mail_title, $mail_txt, $headers );
		exit;
	}

	$up_ids = $attachment_ids;
	require_once( ABSPATH . 'wp-admin/includes/image.php' );
	set_time_limit(0);

	foreach ( $attachment_ids as $attachment_id ) {
		$meta = wp_get_attachment_metadata( $attachment_id );

		$upload_dir = wp_upload_dir( $meta['file'] );
		$sizes = $meta['sizes'];
		if( $sizes ) {
			foreach( $sizes as $size ) {
				$delete_file = $size['file'];
				if( $delete_file && $delete_file != wp_basename( $meta['file'] ) ) {
					$delete_file = $upload_dir['path'] . '/' . $delete_file;
					if( file_exists( $delete_file ) ) {
						unlink( $delete_file );
					}
				}
			}
		}

		$original = $upload_dir['basedir'] . '/' . $meta['file'];
		if( file_exists( $original ) ) {
			if( $attachment_data = wp_generate_attachment_metadata( $attachment_id, $original ) ) {
				$res = wp_update_attachment_metadata( $attachment_id, $attachment_data );
			}
		}
		$unset_key = array_search( $attachment_id, $up_ids );
		unset( $up_ids[$unset_key] );
		$up_id = implode( ',', $up_ids );
		update_option( 'generate_thumbnail_ids', $up_id );
	}
	delete_option( 'generate_thumbnail_ids' );

	bzg_generate_thumbnail_delete_cron();

	//发邮件
	$mail_title = get_bloginfo('name') . '重新生成缩略图任务执行完成';
	$mail_txt = $mail_title . " \n";
	$mail_txt .= '请登录您的主机及网站检查缩略图是否都正确。';
	$headers[] = 'From: '. $blogname .' < ' . $adminemail . '>';
	wp_mail( $blogname . ' <' . $adminemail . '>', $mail_title, $mail_txt, $headers );
}
add_action( 'generate_thumbnail_cron', 'bzg_generate_thumbnail_cron_fun' );

?>
